package com.bsh.controller.user;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cglib.beans.BeanCopier;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.bsh.dto.UserEditDto;
import com.bsh.dto.UserListQryDto;
import com.bsh.mybatis.dataView.UserInfoExt;
import com.bsh.mybatis.model.User;
import com.bsh.service.UserService;
import com.bsh.utils.IpUtil;
import com.bsh.utils.PageJosnMessage;
import com.bsh.utils.PageTools;
import com.bsh.utils.Pager;
import com.bsh.utils.excel.ColumonCfg;
import com.bsh.utils.excel.ExcelExportor;
import com.mysql.jdbc.StringUtils;

@Controller
public class UserController {
	private static Logger log = LoggerFactory.getLogger(UserController.class);

	@Autowired
	HttpServletRequest request;
	@Autowired
	HttpServletResponse response;
	@Autowired
	private UserService userService;

	/**
	 * 用户列表
	 */
	@RequestMapping(value = "/user/list")
	public ModelAndView login(@ModelAttribute UserListQryDto dto) {
		ModelAndView mv = new ModelAndView();
		mv.setViewName("/pages/user/userList");
		
		String pageStr = request.getParameter("pageIndex");
		Integer pageIndex = Integer.parseInt(StringUtils.isNullOrEmpty(pageStr) ? "1" : pageStr);

		String sizeStr = request.getParameter("pageSize");
		Integer pageSize = Integer.parseInt(StringUtils.isNullOrEmpty(sizeStr) ? "10" : sizeStr);

		Pager pager = new Pager(pageIndex, pageSize);
		List<Map<String, Object>> list = userService.getPage(pager,dto);
		mv.addObject("list", list);
		mv.addObject("pager", pager);
		mv.addObject("dto", dto==null?new UserEditDto():dto);
		return mv;
	}
	/**
	 * 用户列表_导出
	 */
	@RequestMapping(value = "/user/list/export")
	public ModelAndView loginExport(@ModelAttribute UserListQryDto dto) {
		ModelAndView mv = new ModelAndView();	
		List<Map<String, Object>> list = userService.getPageExport(dto);
		
		List<ColumonCfg> cfg=new ArrayList<>();		
		cfg.add(new ColumonCfg("name","用户名",150));
		cfg.add(new ColumonCfg("real_name","真实姓名",100));
		cfg.add(new ColumonCfg("sex_ch","性别",60));
		cfg.add(new ColumonCfg("pname","推荐人",100));
		cfg.add(new ColumonCfg("mobile","手机号",120));
		cfg.add(new ColumonCfg("level_ch","用户级别",100));
		cfg.add(new ColumonCfg("ip","登录ip",150));
		cfg.add(new ColumonCfg("is_merchant_ch","是否商户",100));
		cfg.add(new ColumonCfg("create_time_ch","注册时间",130));
		cfg.add(new ColumonCfg("is_effect_ch","状态",100));
		cfg.add(new ColumonCfg("device_type","设备类型",100));
		
		
		ExcelExportor.exportExcelByCfg("会员导出.xls", cfg, list);
		
		return null;
	}
	/**
	 * 修改用户--初使化
	 */
	@RequestMapping(value = "/user/edit/{id}")
	public ModelAndView edit(@PathVariable(value = "id") Integer userid) {
		ModelAndView mv = new ModelAndView();
		mv.setViewName("/pages/user/userEdit");
		UserInfoExt user = userService.getUser(userid);
		mv.addObject("user", user);
		return mv;
	}

	/**
	 * 修改用户--保存
	 */
	@RequestMapping(value = "/user/edit/save")
	public ModelAndView editSave(@ModelAttribute UserEditDto dto) {
		BeanCopier copy = BeanCopier.create(UserEditDto.class, UserInfoExt.class, false);
		UserInfoExt user = new UserInfoExt();
		copy.copy(dto, user, null);
		
		user.setIp(IpUtil.getIpAddr(request));
        Integer res = userService.editUser(user);
        
        ModelAndView mv = new ModelAndView();
		mv.setViewName("/pages/user/userEdit");
		mv.addObject("user", dto);		
		
		String msg = "";
		if (res == -100)
			msg = PageTools.alert("修改用户", "保存失败，推荐人不存在！", 1000,"saveCallback");
		else if (res > 0)
			msg = PageTools.alertCloseFraRefresh("修改用户", "保存成功！", 1000);
		else
			msg = PageTools.alert("修改用户", "保存失败，请稍后重试！", 1000);

		mv.addObject("actionMsg", msg);
		return mv;
	}

	/**
	 * 添加用户--初使化
	 */
	@RequestMapping(value = "/user/add")
	public ModelAndView add() {
		ModelAndView mv = new ModelAndView();
		mv.setViewName("/pages/user/userAdd");
		return mv;
	}

	/**
	 * 添加用户--保存
	 */
	@RequestMapping(value = "/user/add/save")
	public ModelAndView addSave(@ModelAttribute UserEditDto dto) {
		ModelAndView mv = new ModelAndView();		
		mv.setViewName("/pages/user/userAdd");
		mv.addObject("user", dto);	
				
		dto.setCreateTime(new Date());
		BeanCopier copy = BeanCopier.create(UserEditDto.class, UserInfoExt.class, false);
		UserInfoExt user = new UserInfoExt();
		copy.copy(dto, user, null);
		
		String msg = "";		
		if(dto.getPassword()==null||dto.getRePassword()==null ||!(dto.getPassword().equals(dto.getRePassword()))){
			msg = PageTools.alert("添加用户", "保存失败，密码与确认密码不致！", 1000);
			mv.addObject("actionMsg", msg);
			return mv;
		}
		user.setIp(IpUtil.getIpAddr(request));
		Integer res = userService.addUser(user);		

		if (res == -100)
			msg = PageTools.alert("添加用户", "保存失败，推荐人不存在！", 1000,"saveCallback");
		else if (res == -101)
			msg = PageTools.alert("添加用户", "保存失败，"+dto.getMobile()+" 已注册过！", 1000,"saveCallback");
		else if (res == -102)
			msg = PageTools.alert("添加用户", "保存失败，用户名 "+dto.getName()+" 已注册过！", 1000,"saveCallback");
		else if (res > 0)
			msg = PageTools.alertCloseFraRefresh("添加用户", "保存成功！", 1000);
		else
			msg = PageTools.alert("添加用户", "保存失败，请稍后重试！", 1000);

		mv.addObject("actionMsg", msg);
		return mv;
	}


	/**
	 * 查看用户信息
	 */
	@ResponseBody
	@RequestMapping(value = "/user/view/{id}")
	public ModelAndView view(@PathVariable(value = "id") Integer userid) {
		ModelAndView mv = new ModelAndView();
		mv.setViewName("/pages/user/userView");
		
		UserInfoExt user =  userService.getUser(userid);
        //PageJosnMessage msg=new PageJosnMessage();
        //msg.putData("user",user);
        mv.addObject("user",user);
		return mv;
	}
	
	/**
	 * 启用、禁用用户
	 */
	@ResponseBody
	@RequestMapping(value = "/user/enable")
	public PageJosnMessage enable(@RequestParam int id,@RequestParam int isEnable) {
        Integer res =  userService.enableUser(id, isEnable == 1);
        PageJosnMessage msg=new PageJosnMessage();
        res=(res==null?1:res);
        msg.putData("status",res>0?1:0);
		return msg;
	}
	
	/**
	 * 批量禁用
	 */
	@ResponseBody
	@RequestMapping(value = "/user/disable/batch")
	public PageJosnMessage disableBatch(@RequestBody int[] idList) {
        Integer res =  userService.disableBatch(idList);
        PageJosnMessage msg=new PageJosnMessage();
        res=(res==null?1:res);
        msg.putData("status",res>0?1:0);
		return msg;
	}
	
	/**
	 * 批量启用
	 */
	@ResponseBody
	@RequestMapping(value = "/user/enable/batch")
	public PageJosnMessage enableBatch(@RequestBody int[] idList) {
        Integer res =  userService.enableBatch(idList);
        PageJosnMessage msg=new PageJosnMessage();
        res=(res==null?1:res);
        msg.putData("status",res>0?1:0);
		return msg;
	}

	/**
	 * 删除
	 */
	@ResponseBody
	@RequestMapping(value = "/user/delete/{id}")
	public PageJosnMessage delete(@PathVariable(value = "id") Integer id) {
		if(true)return null;
        Integer res =  userService.deleteUser(id);
        PageJosnMessage msg=new PageJosnMessage();
        res=(res==null?1:res);
        msg.putData("status",res>0?1:0);
		return msg;
	}
	
	
	/**
	 * 用户是否存在
	 */
	@ResponseBody
	@RequestMapping(value = "/user/exists")
	public PageJosnMessage exists(@RequestParam(value="userName") String userName) {
		PageJosnMessage msg=null; 
		User user =  userService.getUserByName(userName);
        if(user==null){
        	msg = new PageJosnMessage("400","该用户不存在");
        	msg.putData("mobile","该用户不存在");
        }else{ 
        	msg = new PageJosnMessage("200","用户正确");
            msg.putData("mobile",user.getMobile());
        }
		return msg;
	}	
}
